<div data-title="Code Examples" style="height: 100%;">
  <div class="col-xs-3 main-left-column">
    <div class="list-group upcontrol" id="example-list" style="padding: 0; margin: 0; top: 5px;"></div>
  </div>
  <div class="col-xs-9 main-right-column">
    <div style="margin-top: 5px; ">
      &nbsp;
      <button class="btn btn-sm btn-success" id="copy-example-button"><i class="fa fa-clipboard"></i> 
      Click to replace device's init.js with this example
      and reboot the device</button>
    </div>
    <div class="form-group upcontrol">
      <div id="editor"></div>
    </div>
  </div>
</div>

<script>
  var editor = mkeditor();
  var prefix = 'https://raw.githubusercontent.com/cesanta/mongoose-os/master/fw/examples/mjs_base/examples/';

  $(document).off('click', '.example');
  $(document).on('click', '.example', function() {
    var name = $(this).text();
    var $t = $(this);
    $.get(prefix + name).done(function(text) {
      $('.example').removeClass('selected');
      $t.addClass('selected');
      editor.setValue(text || '', -1);
      editor.session.setMode('ace/mode/' + guesslang(name));
      new PNotify({title: 'Loaded ' + name, type: 'success' });
    });
  });

  $.getJSON(prefix + 'files.json').done(function(json) {
    var $tbody = $('#example-list').empty();
    $.each(json, function(i, v) {
      $('<a href="#" class="list-group-item example"/>').text(v).appendTo($tbody);
    });
  });

  $(document).off('click', '#copy-example-button');
  $(document).on('click', '#copy-example-button', function () {
    var text = editor.getValue();
    return $.ajax({
      url: '/call',
      data: {
        method: 'FS.Put',
        args: JSON.stringify({filename: 'init.js', data: b64enc(text)})
      }
    }).then(function() {
      new PNotify({title: 'Example saved to init.js', type: 'success' });
      return $.ajax({url: '/call', data: {method: 'Sys.Reboot'}});
    }).then(function() {
      new PNotify({title: 'Device reboot successful', type: 'success' });
    });
  });

</script>
